package demo10;

public class Test {

    public int totalFruit(int[] fruits) {
        int n = fruits.length, ret = 0;
        int[] hash = new int[n + 1];
        for (int left = 0, right = 0, kinds = 0; right < n; right++) {
            //进窗口
            int in = fruits[right];
            if (hash[in] == 0) kinds++; //维护水果种类
            hash[in]++;
            //判断
            while (kinds > 2) {
                //出窗口
                int out = fruits[left];
                hash[out]--;
                if (hash[out] == 0) kinds--;
                left++;
            }
            //更新结果
            ret = Math.max(ret, right - left + 1);
        }
        return ret;
    }
}
